system.admin = liwe.module ( "system", null, "Sistema" );

system.admin._modules = [];
system.admin._modactref = {};
system.admin._modules_ref = {};
system.admin._selected_mod = null;
system.admin._selected_action = null;
system.admin._liwe_debug_visible = false;
system.admin._user_info = {};
system.admin._unload = {};
system.admin._curr_mod = null;

liwe.utils.notifier.fx = true;
system.admin.do_alert = function  ( message, mode )
{
        liwe.utils.notifier.show ( message, mode, 2000 );
};


system.admin.init = function ()
{
	this._actions = [
		{ func: function () { system.admin.modules_check (); }, label: "Controllo moduli", 'default': true },
		{ func: function () { system.admin.tables_settings (); }, label: "Impostazioni tabelle" }
	];

	//user.events [ 'login' ] = system.admin._refresh;
	//user.events [ 'logout' ] = system.admin._refresh;
	user.addEventListener ( 'login', system.admin._refresh );
	user.addEventListener ( 'logout', system.admin._refresh );

	system.admin._modules.push ( this );

	system.admin._get_configs ( function ()
	{
		system.load_templates ( function ()
		{
			system.admin._chk_modules ( system.admin._chk_user );
		} )
	} );

	liwe.sound.load ( 'system-sound', '/modules/system/gfx/', [ 'ding.ogg', 'ding.mp3', 'ding.wav' ] );
};

system.admin.get_modules = function () { return system.admin._modules; };

system.admin._get_configs = function ( cback )
{
	cback && cback ();
	return;
	// removed : need testing
	/*
	system.ajax ( { "action": "system.admin.module_get_all_configs" }, function ( v )
	{
		v [ 'config' ].iterate ( function ( confs, mod )
		{
			if ( ! system.admin._modules_ref.get ( mod ) )
			{
				//debugger;
				console.error ( 'system.admin._modules_ref not found' );
			}
			system.admin._modules_ref [ mod ]._config = confs;
			
		} );

		cback && cback ();
	} );
	*/
};

system.admin._chk_modules = function ( cback )
{
	var respawn = false;

	system.admin._modules.iterate ( function ( mod, k )
	{
		console.debug ( "Check Module: %s - Templates: %s", mod.module_name, mod.templates );
		if ( ! mod.templates ) respawn = true;
	} );

	respawn = false;
	
	if ( respawn )
	{
		setTimeout ( function () { system.admin._chk_modules ( cback ); }, 300 );
	} else
		cback ();
};

system.admin._chk_user = function ()
{
	user.ajax ( { 'action' : 'user.ajax.is_logged' }, function ( data )  
					{
						//ASSING SYSTEM MANDATORY TEMPLATE
						liwe.form5.templates [ 'mandatory-clear' ] = system.templates [ 'mandatory-clear' ];
						liwe.form5.templates [ 'mandatory-err' ] = system.templates [ 'mandatory-err' ];
						liwe.form5.templates [ 'mandatory-ok' ] = system.templates [ 'mandatory-ok' ];
						if ( data [ 'uid' ] )
						{
							system.admin.modules_accordion ();
							system.admin._show_user_info ();
							system.admin._dashboard ();
							return;
						} 
						$( 'system-toolbar-modules' , '' );
						//user.login_box ();
						//ASSIGN SYSYTEM LOGIN TEMPLATE
						if ( ! user.templates )
						{
							user.load_templates ( system.admin._chk_user );
							return;
						}
						user.templates [ 'frm-user-layout' ] = String.formatDict ( system.templates [ 'frm-user-layout'], { title: $( 'system-login' ).title } );
						user.templates [ "frm-login" ] = system.templates [ 'frm-login' ];
						user.templates [ 'frm-registration' ] = system.templates [ 'frm-registration' ];
						user.templates [ 'frm-lost-pwd' ] = system.templates [ 'frm-lost-pwd' ];
						//Load login box
						user.render_login ( 'system-login', null, "system" ); 	
					} );
};

system.admin._show_user_info = function ()
{
	user.ajax ( { action : 'user.ajax.get_info' } , function ( data ) 
							{
								console.debug ( data );
								system.admin._user_info = data;
								system.admin._liwe_debug_init ();
								$( 'sys_topnav', String.formatDict ( system.templates [ 'login_info' ],
														data ), true );
							} ); 
};


system.admin._set_selected = function ( div_sel )
{
	var div_name = ''; 
	system.admin._modules.iterate ( function ( v, k ) 
					{
						div_name = 'button:toolbar:system-modules-btn' + k;
						$( div_name ).firstChild.style.backgroundPosition = 'center bottom';
						//console.debug ( "button:toolbar => div: %s - sel: %s - value: %o" , div_name , div_id, $( div_name ) );
					} ); 
	console.debug ( div_sel );
	$( div_sel ).firstChild.style.backgroundPosition = 'center top';
};

system.admin.module_register = function ( mod )
{
	console.debug ( "Mod: %s - ACTS: %o", mod.module_name, mod._actions );

	system.admin._modactref [ mod.module_name ] = mod._actions;

	system.admin._modules.push ( mod );
	// system.admin._modules_ref [ mod.module_name.split ( "." ) [ 0 ] ] = mod;

	system.admin._modules.sort ( function ( v1, v2 ) { return v1.module_name > v2.module_name; } );
};

system.admin._dashboard = function ()
{
	return;

/*
	var dct = {};
	var mods = [];
	var res = new String.buffer ();

	res.add ( system.templates [ 'dash-start' ] );
	res.add ( system.templates [ 'dash-box-start' ] );

	system.admin._modules.iterate ( function ( mod )
	{
		if ( mod.has_dashboard )
		{
			mods.push ( mod );
			dct [ 'name' ] = mod.module_name;
			dct [ 'label' ] = mod.label;
			res.add ( String.formatDict ( system.templates [ 'dash-panel' ], dct ) );
		}

	} );

	res.add ( system.templates [ 'dash-box-end' ] );
	res.add ( system.templates [ 'dash-end' ] );
	
	$( "system-content", res.toString () );

	mods.iterate ( function ( mod )
	{
		mod.get_dashboard ( function ( content, title )
		{
			$( 'dash-content-' + mod.module_name, content );
			if ( title )
				$( 'dash-title-' + mod.module_name, title );
		} );
	} );
*/
};

system.admin.modules_accordion = function ()
{
	var acc_name = "sys-modules";
	var acc = new WWL.accordion ( acc_name );
	acc.auto_close= false;
	var dct = {};

	system.admin._modules.iterate ( function ( mod, mod_pos )
	{
		if ( ! mod._actions && ! mod._config ) return;

		var content = new String.buffer ();
		content.add ( system.templates [ 'accordion-start' ] ) // '<ul class="accordion_module">' );

		mod._actions.iterate ( function ( act, pos )
		{
			// create unload functions list
			if ( act [ 'label' ] == 'unload' )
			{
				system.admin._unload [ mod_pos ] = act [ 'func' ];
				return;
			}	
		
			dct [ 'label' ] = act [ 'label' ];
			dct [ 'pos' ] = pos;
			dct [ 'mod_pos' ] = mod_pos;
			dct [ 'mod_name' ] = mod.module_name;
			dct [ 'acc' ] = acc_name;
			dct [ 'el_id' ] = acc_name + ':' + mod.module_name + ':' + pos;

			content.add ( String.formatDict  ( system.templates  [ 'accordion-el' ], dct  ) )   // ( tmpl, dct ) );
		} );

		if ( mod._config )
			content.add ( String.formatDict ( system.templates [ 'accordion-el-cfg' ], { "_modname" : mod.module_name } ) );
		
		content.add  ( system.templates [ 'accordion-end' ] )  // ( "</ul>" );

		acc.add_item ( { txt: mod.label, content: content.toString () } );
	} );

	acc.render ( 'sys_accordion' );
};

system.admin._config_form = function ( full_mod_name )
{
	var mod_name = full_mod_name.split ( "." ) [ 0 ];
	var mod = system.admin._modules_ref [ mod_name ];
	var f = new liwe.form.instance ( "module-config" );
	
	f.hidden ( "module_name", mod_name );
	f.hidden ( "action", "system.admin.module_config_save" );

	mod._config.iterate ( function ( row )
	{
		f [ row [ 'type' ] ] ( row );
	} );

	f.button ( { "value" : "Salva", onclick: "system.admin._config_save ()", ignore: true } );

	f.set ( "system-content" );
};

system.admin._config_save = function ()
{
	var f = liwe.form.get ( "module-config" );
	var v = f.get_values ();

	system.ajax ( v, function ( v )
	{
		system.admin.do_alert ( "Configurazione salvata correttamente", "info" );
	} );
};

system.admin._set_acc_selected = function ( mod_name, act_pos, acc )
{
	// selected action
	var sel_id = acc + ':' + mod_name + ':' + act_pos;
	var sel_class = 'act_selected';
	//var tmp_lst = document.getElementsByClassName ( sel_class );
	// FIX for IE
	var tmp_lst = $c( 'li', sel_class, $( 'sys-accordion' ) );
	if ( tmp_lst ) liwe.dom.del_class ( tmp_lst [ 0 ], sel_class );
	liwe.dom.add_class ( $( sel_id ), sel_class );
	system.admin._selected_action = sel_id;
	
};

system.admin._action = function ( mod_name, act_pos, acc )
{
	//var mod = system.admin._modules [ mod_pos ];

	var actions = system.admin._modactref [ mod_name ];
	var act = actions [ act_pos ];

	//system.admin._set_acc_selected ( mod_pos, act_pos, acc );

	system.admin._unload_mods ( mod_name );
	system.admin._curr_mod = mod_name;
	act [ 'func' ] ();
};

system.admin._unload_mods = function ( mod_name )
{
	//jconed clearing
	if ( typeof ( jconed ) != 'undefined' && jconed.editor.get ( 'current' ) )
	{
		jconed.editor.current.detach ();
	}	

	if ( system.admin._curr_mod == null || system.admin._curr_mod == mod_name ) 
		return;
		
	var func = system.admin._unload.get ( system.admin._curr_mod );
	if ( func ) func ();
};


system.admin.login_form = function ()
{
	var f = new liwe.form.instance ( 'system_login_form', 'user.ajax.login' );
	f.text ( { label: 'user', name: 'login', mandatory: true } );
	f.password ( { label: 'password', name: 'pwd', mandatory: true } );
	f.submit ( 'Log In' );
	f.set ( 'system-login' );
};

system.admin._refresh = function ()
{
	document.location.reload ( true );
};

system.admin.expand = function ()
{
	if ( liwe.dom.has_class ( document.body, 'expanded' ) )
		liwe.dom.del_class ( document.body, 'expanded' );
	else
		liwe.dom.add_class ( document.body, 'expanded' );
};

system.admin.reload_templates = function ()
{
	system.load_templates ( function () { console.debug ( 'templates reloaded for "system"' ); } );
	system.admin._modules.iterate ( function ( v )
	{
		var m = v.module_name.substr ( 0, v.module_name.length - 6 );
		if ( m == 'tags' ) return;
		if ( window.get ( m ) )
		{
			var module = window [ m ];
			module.templates = null;
			module.load_templates ( function () { console.debug ( 'templates reloaded for "%s"', m ); } );
		}
	} );
};

system.admin._liwe_debug_init = function ()
{
	if ( system.admin._user_info.get ( 'login' ) != 'root' ) return;

	$( 'sys_top', system.templates [ 'liwe-debug' ] );

	var f = new liwe.form.instance ( 'ajax-test' );
	f.text ( { name: 'action', label: 'Action', nonl: true } );
	f.label ( { value: 'LiWE Ajax Test Form' } );
	for ( var i = 0; i < 5; i++ )
	{
		f.text ( { name: 'name-' + i, label: 'Name', nonl: true } );
		f.text ( { name: 'value-' + i, label: 'Value', size: 23 } );
	}
	f.button ( { value: 'Go', onclick: 'system.admin._ajax_test()', 'class': 'orange' } );
	f.set ( 'ajax-test-form' );

	var buttons = '<button class="orange" onclick="liwe.dom.reload_css()">Reload CSS</button>&nbsp;' +
		'<button class="orange" onclick="system.admin.reload_templates()">Reload TPL</button>';
	$( 'liwe-debug-actions', buttons );
};

system.admin._liwe_debug_toggle = function ()
{
	if ( system.admin._user_info.get ( 'login' ) != 'root' ) return;

	if ( system.admin._liwe_debug_visible )
		liwe.dom.del_class ( $( 'liwe-debug-container' ), 'liwe-debug-visible' );
	else
		liwe.dom.add_class ( $( 'liwe-debug-container' ), 'liwe-debug-visible' );

	system.admin._liwe_debug_visible = ! system.admin._liwe_debug_visible;
};

system.admin._ajax_test = function ()
{
	var f = liwe.form.get ( 'ajax-test' );
	var vals = f.get_values ();

	var action = vals [ 'action' ];

	if ( ! /\w+\.\w+\.\w+/.test ( action ) )
	{
		liwe.utils.notifier.show ( 'Invalid action specified: "<b>' + action + '</b>". Format is <i>( $module ) . ( $file ) . ( $function )</i>', 'warn', 5000 );
		return;
	}

	var params = {};
	params [ 'action' ] = vals [ 'action' ];
	for ( var i = 0; i < 5; i++ )
		if ( vals [ 'name-' + i ] && vals [ 'value-' + i ] )
			params [ vals [ 'name-' + i ] ] = vals [ 'value-' + i ];

	system.admin.ajax ( params, function ( res )
	{
		console.debug ( res );
	} );
};

system.admin.modules_check = function ()
{
	var res = new String.buffer ();

	res.add ( system.templates [ "mod-check-head" ] );
	system.admin.ajax ( { action: "system.admin.modules_check" }, function ( v )
	{
		v [ 'check' ].iterate ( function ( mod )
		{
			res.add ( String.formatDict ( system.templates [ "mod-check-row-start" ], mod ) );
			if ( mod [ 'checks' ].count() == 0 )
				res.add ( system.templates [ "mod-check-nodata" ] );
			else
			{
				res.add ( String.formatDict ( system.templates [ "mod-check-table-start" ], mod ) );
				mod [ 'checks' ].iterate ( function ( val )
				{
					res.add ( String.formatDict ( system.templates [ "mod-check-data" ], val ) );
				} );
				res.add ( String.formatDict ( system.templates [ "mod-check-table-end" ], mod ) );
			}
			res.add ( String.formatDict ( system.templates [ "mod-check-row-end" ], mod ) );
		} );

		res.add ( system.templates [ "mod-check-end" ] );
		$( "system-content", res.toString () );
	} );
};

system.admin.tables_settings = function ()
{
	system.admin.ajax ( { action: "system.admin.tables_settings" }, function ( res )
	{
		var buf = new String.buffer ();

		buf.add ( system.templates [ "tables-start" ] );

		res [ 'tables' ].iterate ( function ( row )
		{
			buf.add ( String.formatDict ( system.templates [ "tables-row" ], row ) );
		} );

		buf.add ( system.templates [ "tables-end" ] );

		$( "system-content", buf.toString () );
	} );
};
